package com.losdun.weixin.manager;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.losdun.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author Sword.Ye
 * @Date 2025/9/23
 **/
@Slf4j
public class MessageManager {


    /**
     * 发送消息
     * @param templateId
     * @param openId
     * @param msgData
     * @param url
     */
    public static void sendMessage(String templateId, String openId, List<WxMaSubscribeMessage.MsgData> msgData, String url) {
        WxMaSubscribeMessage msg=WxMaSubscribeMessage.builder()
                .templateId(templateId).toUser(openId).page(url).data(msgData).build();
        try {
            getWxMaService().getMsgService().sendSubscribeMsg(msg);
        } catch (WxErrorException e) {
            log.error("发送消息失败,templateId:{},openId:{},errMsg:{}",templateId,openId,e.getMessage(),e);
        }
    }

    /**
     * 发送消息
     * @param templateId
     * @param openId
     * @param msgData
     */
    public static void sendMessage(String templateId, String openId, List<WxMaSubscribeMessage.MsgData> msgData) {
        sendMessage(templateId,openId,msgData,null);
    }

    /**
     * 批量发送消息
     * @param openIds
     * @param templateId
     * @param msgData
     * @param url
     */
    public static void batchSendMessage(List<String> openIds, String templateId, List<WxMaSubscribeMessage.MsgData> msgData, String url){
        for (String openId : openIds) {
            sendMessage(templateId,openId,msgData,url);
        }
    }


    /**
     * 预约成功消息
     * @param name
     * @param phone
     * @param dateTime
     * @param address
     * @param item
     * @return
     */
    public static List<WxMaSubscribeMessage.MsgData> buildBookSuccessMsgData(String name, String phone,String dateTime,String address,String item){
        List<WxMaSubscribeMessage.MsgData> list=new ArrayList<>();
        list.add(new WxMaSubscribeMessage.MsgData("thing2",name));
        list.add(new WxMaSubscribeMessage.MsgData("phone_number3",phone));
        list.add(new WxMaSubscribeMessage.MsgData("time4",dateTime));
        list.add(new WxMaSubscribeMessage.MsgData("thing5",address));
        list.add(new WxMaSubscribeMessage.MsgData("thing5",item));
        return list;
    }

    private static WxMaService getWxMaService(){
        return SpringUtils.getBean(WxMaService.class);
    }
}
